package layeredcontent.domains.account.commands
{
	import flash.events.FileListEvent;
	import flash.filesystem.File;
	
	import flight.domain.AsyncCommand;
	
	import layeredcontent.domains.account.AccountDomain;
	import layeredcontent.domains.account.model.Account;

	public class CommandLoadAccounts extends AsyncCommand
	{
		public var client:AccountDomain;
		
		public function CommandLoadAccounts()
		{
			
		}
		
		public override function execute():void
		{
			var file:File = File.applicationStorageDirectory.resolvePath("accounts");
			if (!file.exists) {
				file.createDirectory();
				client.model.accounts = [];
				complete();
			} else {
				file.addEventListener(FileListEvent.DIRECTORY_LISTING, onAccountListing);
				file.getDirectoryListingAsync();
			}
		}
		
		protected function onAccountListing(event:FileListEvent):void
		{
			if (!event.files.length) {
				client.model.accounts = [];
				cancel();
				return;
			}
			
			var accounts:Array = [];
			for each (var file:File in event.files) {
				if (file.isDirectory) {
					accounts.push(new Account(file.name));
				}
			}
			
			client.model.accounts = accounts;
		}
	}
}